package com.kidback.bbloc259.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewbinding.ViewBinding;

import com.kidback.bbloc259.util.CollectionUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;

/**
 * Created by meikai on 2020/06/02.
 */
public abstract class BaseFragment<T extends ViewBinding> extends Fragment {

    public List<Disposable> disposableList = new ArrayList<>();

    public T viewBinding;
    protected LayoutInflater inflater;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        viewBinding = getViewBinding(container);

        if (viewBinding != null) {
            return viewBinding.getRoot();
        } else {
            return super.onCreateView(inflater, container, savedInstanceState);
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        loadData();

        EventBus.getDefault().register(this);
    }

    public abstract T getViewBinding(ViewGroup container);

    protected abstract void initView();

    protected abstract void loadData();

    protected String getPageName() {
        return this.getClass().getSimpleName();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNoneEvent(Object object) {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

        for (int i = 0; i < CollectionUtils.size(disposableList); i++) {
            Disposable disposable = CollectionUtils.get(disposableList, i);
            if (disposable != null && !disposable.isDisposed()) {
                disposable.dispose();
            }
        }
    }

}
